<?php
	class SmfApi extends AppModel
	{
		var $name = "SmfApi";
		var $useTable = "smf_api";
		private $smfActive = false;
		const SMF_DS_NAME = "smf_db";
		private $smfDb = false;
		private $smfSettings = array();
		function afterInitialize()
		{
			if(!cr("SmfConfig"))
			{
				cri("Smf.SmfConfig")->init();
			}
			if(cr("SmfConfig.forum_path") && checkSessionKey('smf'))
			{
				$settingsFile = cr("SmfConfig.forum_path").DS.'Settings.php';
				if(is_file($settingsFile))
				{
					include $settingsFile;
					$settings = compact('boardurl','cookiename','db_type','db_server','db_name','db_user',
							'db_passwd','ssi_db_user','db_prefix');
					$this->smfActive = true;
					$this->smfSettings  = $settings;
				}
			}
		}
		
		function login($userId,$cookieLength = 3600)
		{
			if(!is_numeric($cookieLength))
			{
				$cookieLength = 3600;
			}
			$smfId = $this->field("smf_user_id",array("user_id"=>$userId));
			if(!$smfId)
			{
				//register At runtime.
				$UserModel = cri("Users.User");
				$UserModel->recursive = -1;
				$userInfo = $UserModel->findById($userId);
				$smfId = $this->register($userId, $userInfo['User']);
			}
			if($smfId)
			{
				$MemberModel = $this->getSmfDbTableModel("members");
				$member = $MemberModel->findByIdMember($smfId);
				if($member)
				{
					$member = $member[$MemberModel->alias];
					$this->setLoginCookie($cookieLength,$member['id_member'],sha1($member['passwd'] . $member['password_salt']));
				}
			}
		}
		function updateSmfUser($userId,$userInfo)
		{
			$smfId = $this->field("smf_user_id",array("user_id"=>$userId));
			if($smfId)
			{
				$info = array("member_name"=>$userInfo['username'],'email_address'=>$userInfo['email']);
				$MemberModel = $this->getSmfDbTableModel("members");
				$member = $MemberModel->findByIdMember($smfId);
				$member = $member[$MemberModel->alias];
				if($member)
				{
					$member = am($member,$info);
					$MemberModel->create();
					$MemberModel->primaryKey = "id_member";
					$MemberModel->id = $member['id_member'];
					$MemberModel->save(array($MemberModel->alias=>$member));
				}
			}
		}
		function register($userId,$userInfo,$extraFields = array())
		{
			$MemberModel = $this->getSmfDbTableModel('members');
			$presentUserId = $this->field('smf_user_id',array('user_id'=>$userId));
			if($presentUserId)
			{
				if($presentUserId)
				{
					if($MemberModel->hasAny(array("id_member"=>$presentUserId)) == false)
					{
						$this->deleteAll(array('smf_user_id'=>$presentUserId));
						$presentUserId = null;
					}else
					{
							return $presentUserId;
					}
				}
			}
			$username = $userInfo['username'];
			$email = $userInfo['email'];
			$ip = Utility::getClientIP();
			if(isset($userInfo['lastLoginIpAddr']) && strlen($userInfo['lastLoginIpAddr']))
			{
				$ip = $userInfo['lastLoginIpAddr'];
			}
			$passwordToken = Utility::generateRandomCode(5); 
			$password = sha1(strtolower($username) . $passwordToken);
			$realName = $username;
			$registerVars = array(
				'member_name' => $username,
				'date_registered' => time(),
				'posts' => 0,
				'real_name' => $realName,
				'passwd' => $password,
				'email_address' =>$email,	
				'member_ip' => $ip,
				'member_ip2'=>$ip,
				'id_post_group' => 4,	
				'password_salt' => substr(md5(rand()), 0, 4),
				'is_activated' => 1,
				'pm_email_notify' => 1,
				'id_theme' => 0,
			);
			$MemberModel = $this->getSmfDbTableModel('members');
			$data = array($MemberModel->alias => $registerVars);
			$MemberModel->create();
			$id = false;
			if($MemberModel->save($data))
			{
				$id = $MemberModel->id;
				$apiData = array("user_id"=>$userId,'smf_user_id'=>$id,'password_token'=>$passwordToken);
				$this->create();
				$this->save(array($this->alias => $apiData));
			}
			if($id)
			{
				$totMembers = $MemberModel->find("count");
				$SettingsModel = $this->getSmfDbTableModel("settings");
				$SettingsModel->updateAll(array("value"=>$SettingsModel->getDataSource()->value($totMembers)),array('variable'=>'totalMembers'));
				$SettingsModel->updateAll(array('value'=>$SettingsModel->getDataSource()->value($username)),array("variable"=>'latestMember'));
				$SettingsModel->updateAll(array('value'=>$SettingsModel->getDataSource()->value($realName)),array("variable"=>'latestRealName'));
				$LogActivityModel = $this->getSmfDbTableModel("log_activity");
				$LogActivityModel->updateAll(array('registers'=>"registers + 1"),array("date"=>strftime('%Y%m%d')));
				if($LogActivityModel->getAffectedRows() == 0)
				{
					$LogActivityModel->create();
					$LogActivityModel->save(array($LogActivityModel->alias => array('registers'=>1,'date'=>strftime('%Y%m%d'))));
				}
			}
			return $id;
		}
		function setLoginCookie($length,$memberId,$password)
		{
			//keep it simple...let the login be good for anywhere from anywhere on the domain.
			$this->smfSettings['globalCookies']=1;
			$cookieState = (empty($this->smfSettings['localCookies']) ? 0 : 1) | (empty($this->smfSettings['globalCookies']) ? 0 : 2);   
			if (isset($_COOKIE[$this->smfSettings['cookiename']]))
			{
				$array = @unserialize($_COOKIE[$this->smfSettings['cookiename']]);
				if (isset($array[3]) && $array[3] != $cookie_state)
				{
					$parsed_url = $this->getCookieUrl($array[3] & 1 > 0, $array[3] & 2 > 0);
					setcookie($this->smfSettings['cookiename'], serialize(array(0, '', 0)), time() - 3600, $parsed_url['path'] . '/', $parsed_url['host'], 0);
				}
			}
			// Get the data and path to set it on.
			$parsed_url = $this->getCookieUrl(!empty($this->smfSettings['localCookies']), !empty($this->smfSettings['globalCookies']));
			$data = serialize(empty($memberId) ? array(0, '', 0) : array($memberId, $password, time() + $length));
			// Set the cookie, $_COOKIE, and session variable.
			setcookie($this->smfSettings['cookiename'], $data, time() + $length, $parsed_url['path'] . '/', $parsed_url['host'], 0);
			$_COOKIE[$this->smfSettings['cookiename']] = $data;
			$_SESSION['login_' . $this->smfSettings['cookiename']] = $data;
			return true;
		}
		function getCookieUrl($local, $global)
		{
			$parsed_url = parse_url($this->smfSettings['boardurl']);
			if (isset($parsed_url['port']))
			{
				$parsed_url['host'] .= ':' . $parsed_url['port'];
			}
			// Set the cookie to the forum's path only?
			if (empty($parsed_url['path']) || !$local)
				$parsed_url['path'] = '';

		// This is probably very likely for apis and such, no?
			if ($global)
			{
				// Try to figure out where to set the cookie; this can be confused, though.
				$parts = array();
				if (preg_match('~(?:[^\.]+\.)?(.+)\z~i', $parsed_url['host'], $parts) == 1)
					$parsed_url['host'] = '.' . $parts[0];
			}
			// If both options are off, just use no host and /.
			elseif (!$local)
				$parsed_url['host'] = '';

			return $parsed_url;
		}
		function logOut()
		{
			$info = @unserialize($_SESSION['login_'.$this->smfSettings['cookiename']]);
			if(isset($info['0']) && $info['0'] > 0)
			{
				$LogOnlineModel = $this->getSmfDbTableModel("log_online");
				$memberId = $LogOnlineModel->getDataSource()->value((int)$info['0']);
				$LogOnlineModel->query("Delete from $LogOnlineModel->tablePrefix$LogOnlineModel->table where id_member = $memberId");
			}
			$this->setLoginCookie(-3600,0,"");
			$parsed_url = $this->getCookieUrl(false, true);
			setcookie("PHPSESSID", "", time() - 3600, $parsed_url['path'] . '/', $parsed_url['host'], 0);
		}
		private function getSmfDbTableModel($table)
		{
			$this->getSmfDataSource();
			$alias = Inflector::camelize($table);
			$model = new AppModel(array("table"=>$table,'ds'=>self::SMF_DS_NAME,'name'=>$alias,'alias'=>$alias,));
			return $model;
		}

		private function getSmfDataSource()
		{
			if(!isset($this->smfDb) || $this->smfDb == false)
			{
				$dbSettings = array('driver'=>"mysql","persistent"=>false,'database'=>$this->smfSettings['db_name'],'db_server'=>$this->smfSettings['db_server'],
					'login'=>$this->smfSettings['db_user'],'password'=>$this->smfSettings['db_passwd'],'prefix'=>$this->smfSettings['db_prefix']);
				ConnectionManager::create(self::SMF_DS_NAME, $dbSettings);
				$this->smfDb = ConnectionManager::getDataSource(self::SMF_DS_NAME);
			}
			return 	$this->smfDb;	
		}
		
		function deleteSmfUser($userId)
		{
			$smfUserId = $this->field('smf_user_id',array("user_id"=>$userId));
			if(!$smfUserId)
			{
				return;
			}
			$SettingsModel = $this->getSmfDbTableModel("settings");
			$MessageModel = $this->getSmfDbTableModel("messages");
			$MemberModel = $this->getSmfDbTableModel("members");
			$allowHideEmail = $SettingsModel->hasAny(array('variable'=>"allow_hideEmail",'value'=>1));
			$updateCon = array("id_member"=>0);
			if($allowHideEmail)
			{
				$updateCon['poster_email'] = "";
			}
			$MessageModel->updateAll($updateCon,array("id_member"=>$smfUserId));
			$PersonnelMessageModel = $this->getSmfDbTableModel("personal_messages");
			$PersonnelMessageModel->updateAll(array('id_member_from'=>0),array('id_member_from'=>$smfUserId));
			$updateTables = array("polls","log_actions","log_banned","log_errors","log_topics",);
			foreach($updateTables as $updateTable)
			{
				$MemberModel->query("UPDATE $MemberModel->tablePrefix$updateTable SET id_member = 0 where id_member = $smfUserId");
			}
			
			$deleteLogs = array("log_boards","log_mark_read","log_notify","log_online","log_polls","log_topics","collapsed_categories","moderators",
				"ban_items","themes");
			foreach($deleteLogs as $deleteLogTable)
			{
				$MemberModel->query("DELETE FROM $MemberModel->tablePrefix$deleteLogTable where id_member = $smfUserId");
			}
			$deleteLogTable = "log_karma";
			$MemberModel->query("DELETE FROM $MemberModel->tablePrefix$deleteLogTable where id_executor = $smfUserId");
			$MemberModel->primaryKey = "id_member";
			$MemberModel->del($smfUserId);
			$this->deleteAll(array("user_id"=>$userId));
	}
}
?>